package cqie.cn.frame.shirospringboot.controller;

import cqie.cn.frame.shirospringboot.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

/**
 * @author 王林
 * @version 1.0
 * @date 2021-09-10 周五
 * @time 20:49
 * @description 自定义的 UserRealm
 */
public class UserRealm extends AuthorizingRealm {
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权===》doGetAuthorizationInfo");

        //授权 SimpleAuthorizationInfo
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addStringPermission("user:add");

        // 拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal(); // 拿到User对象

        //设置当前用户的权限
        info.addStringPermission(currentUser.getPermission());

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证===》doGetAuthenticationInfo");

        //用户名 ， 密码    数据库中取
//        String name = "root";
//        String password = "123456";
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        User user = new User();
        user.setUsername("root");
        user.setPassword("123456");
//        user.setPermission("user:add");

//        if (!userToken.getUsername().equals(name)) {
//            return null;   // 用户名错我，返回空会抛出异常  UnknownAccountException
//        }

        if (user == null) {
            return null;
        }

        //可以加密 MD5 4……I^^&*^&8YUITYYUIT      MD5盐值加密  RERERER……&*%……& username
        // 密码认证， shiro做~~~~
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
    }
}
